﻿using Ongoal.Quotation.Common;
using Ongoal.Quotation.Cap;
using Ongoal.Quotation.Service;
using Ongoal.Quotation.Service.Common;
using Ongoal.Quotation.Service.Interface;
using Ongoal.Quotation.Service.Model;
using Ongoal.Quotation.Model;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ongoal.Quotation.Service
{
    /// <summary>
    /// 用户服务
    /// </summary>
    public class OrganizeService : ServiceBase, IOrganizeService
    {
        private IMessagePublisher _messagePublisher;
        public OrganizeService(IMessagePublisher messagePublisher)
        {
            _messagePublisher = messagePublisher;
        }

        /// <summary>
        /// 根据父ID获取组织结构
        /// </summary>
        /// <returns></returns>
        public object GetOrganizeByParentId(int ParentId, int?[]? state, string? keyword)
        {
            using (SqlSugarClient db = Db.GetDbContext(""))
            {
                if (state != null)
                {
                    state = state.Where(s => s != null).ToArray();
                }
                var result = db.Queryable<Organize, Organize>((z, j) => new object[] {
                    JoinType.Left, z.ParentID == j.ID
                }).Where((z, j) => z.ParentID == ParentId && z.Deleted == 0)
                .WhereIF(state != null && state.Any(),z => state!.Contains(z.Enable))
                .WhereIF(!string.IsNullOrEmpty(keyword),z => z.OrgName!.Contains(keyword!) || z.OrgCode!.Contains(keyword!))
                .Select((z, j) => new
                {
                    FullName = z.FullName,
                    CreateTime = z.CreateTime,
                    CreatorID = z.CreatorID,
                    Deleted = z.Deleted,
                    Enable = z.Enable,
                    ID = z.ID,
                    ModifyID = z.ModifyID,
                    ModifyTime = z.ModifyTime,
                    NodeLevel = z.NodeLevel,
                    OrderCode = z.OrderCode,
                    OrgCode = z.OrgCode,
                    OrgLogo = z.OrgLogo,
                    OrgName = z.OrgName,
                    OrgType = z.OrgType,
                    parentId = z.ParentID,
                    PropPath = z.PropPath,
                    Remark = z.Remark,
                    Haschilds = z.IsLeafNode,
                    jid = j.ID,
                    jname = j.OrgName
                }).ToList().Select(z => new
                {
                    FullName = z.FullName,
                    CreateTime = z.CreateTime,
                    CreatorID = z.CreatorID,
                    Deleted = z.Deleted,
                    Enable = Convert.ToBoolean(z.Enable),
                    ID = z.ID,
                    ModifyID = z.ModifyID,
                    ModifyTime = z.ModifyTime,
                    NodeLevel = z.NodeLevel,
                    OrderCode = z.OrderCode,
                    OrgCode = z.OrgCode,
                    OrgLogo = z.OrgLogo,
                    OrgName = z.OrgName,
                    OrgType = z.OrgType,
                    parentId = z.parentId,
                    PropPath = z.PropPath,
                    Remark = z.Remark,
                    IsLeafNode = z.Haschilds,
                    Haschilds = !Convert.ToBoolean(z.Haschilds),
                    parentname = z.jname == null ? "无" : z.jname
                });
                //修改当前节点为叶子节点
                if (result.Count() == 0)
                {
                    var modelentity = db.Queryable<Organize>().Where(z => z.ID == ParentId).ToList().FirstOrDefault();
                    if (modelentity != null)
                    {
                        modelentity.IsLeafNode = 1;
                        db.Updateable<Organize>(modelentity).ExecuteCommand();
                    }
                }
                return result;
            }

        }

        /// <summary>
        /// 获取组织结构树
        /// </summary>
        /// <returns></returns>
        public object GetOrganizeTree()
        {
            using (var db = Db.GetDbContext(String.Empty))
            {
                List<Organize> treelist = new List<Organize>();
                var all = db.Queryable<Organize>().Where(z => z.Deleted == 0).OrderBy(z => z.OrderCode).ToList();
                foreach (var item in all)
                {
                    var parent = all.Where(z => z.ID == item.ParentID).FirstOrDefault();
                    if (parent != null)
                    {
                        if (parent.Children == null)
                        {
                            parent.Children = new List<Organize>();
                        }
                        parent.Children.Add(item);
                    }
                    else if(item.ParentID == 0)
                    {
                        treelist.Add(item);
                    }


                }
                return treelist;
            }

        }

        /// <summary>
        /// 添加组织结构
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool AddOrganizelist(Organize model)
        {
            try
            {
                checkdata(model, 1);
                Organize? parent=null ;
                if (model.ParentID != 0)
                {
                    using (var db = Db.GetDbContext(String.Empty))
                    {
                        parent = db.Queryable<Organize>().Where(z => z.ID == model.ParentID).ToList().FirstOrDefault();
                        //if (parent != null && (!parent.IsLeafNode.HasValue || parent.IsLeafNode != 0))
                        //{
                        //    parent.IsLeafNode = 0;
                        //    db.Updateable<Organize>(parent).ExecuteCommand();
                        //}
                    }
                }
                this.InsertAndPublish<Organize>(model,_messagePublisher, MessageConstant.Department, (client) => {
                    if (parent != null && (!parent.IsLeafNode.HasValue || parent.IsLeafNode != 0))
                    {
                        parent.IsLeafNode = 0;
                        client.Updateable<Organize>(parent).ExecuteCommand();
                    }
                    return true;
                });
                //_messagePublisher.PublishWithDefaultCallback(MessageConstant.Department, model);//推送数据
                return true;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }

        /// <summary>
        /// 修改组织结构
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateOrganizelist(Organize model)
        {
            try
            {
                checkdata(model, 2);
                this.UpdateAndPublish<Organize>(model, _messagePublisher, MessageConstant.Department);
                // _messagePublisher.PublishWithDefaultCallback(MessageConstant.Department, model);//推送数据
                return true;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }

        public bool checkdata(Organize model, int checktype)
        {
            using (var db = Db.GetDbContext(""))
            {
                if (checktype == 1) //新增
                {
                    if (db.Queryable<Organize>().Any(z => z.OrgCode == model.OrgCode && z.ParentID == model.ParentID && z.Deleted != 1))
                    {
                        throw new Exception("编码已经存在");
                    }
                    if (db.Queryable<Organize>().Any(z => z.OrgName == model.OrgName && z.ParentID == model.ParentID && z.Deleted != 1))
                    {
                        throw new Exception("名称已经存在");
                    }
                }
                else
                { //编辑
                    if (db.Queryable<Organize>().Any(z => z.OrgCode == model.OrgCode && z.ParentID == model.ParentID && z.ID != model.ID && z.Deleted != 1))
                    {
                        throw new Exception("编码已经存在");
                    }
                    if (db.Queryable<Organize>().Any(z => z.OrgName == model.OrgName && z.ParentID == model.ParentID && z.ID != model.ID && z.Deleted != 1))
                    {
                        throw new Exception("名称已经存在");
                    }
                }
                return true;

            }
        }
        /// <summary>
        /// 删除组织结构
        /// </summary>
        /// <param name="listid"></param>
        /// <returns></returns>
        public bool DeleteOrganizelist(List<int> listid)
        {
            try
            {
                //连级删除
                using (var db = Db!.GetDbContext(string.Empty))
                {
                    var all = db.Queryable<Organize>().Where(z => z.Deleted == 0).ToList();
                    foreach (var item in all)
                    {
                        if (listid.Any(s => s == item.ParentID))
                            listid.Add(item.ID);
                    }
                }

                bool result = this.DeleteAndPublish<Organize>(listid.ToArray(), _messagePublisher, MessageConstant.DeleteDepartment);
                //if (result)
                //    _messagePublisher.PublishWithDefaultCallback(MessageConstant.DeleteDepartment, listid);//推送数据
                return result;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
